import { REAL_TYPE } from '../../constants';

/**
 * Descending comparator for sorting
 */
export function descendingComparator<T>(a: T, b: T, orderBy: keyof T): number {
  if (b[orderBy] < a[orderBy]) {
    return -1;
  }
  if (b[orderBy] > a[orderBy]) {
    return 1;
  }
  return 0;
}

/**
 * Get comparator function based on order
 */
export function getComparator<T>(
  order: 'asc' | 'desc',
  orderBy: keyof T,
): (a: T, b: T) => number {
  return order === 'desc'
    ? (a: T, b: T) => descendingComparator(a, b, orderBy)
    : (a: T, b: T) => -descendingComparator(a, b, orderBy);
}

/**
 * Stable sort function that maintains order for equal elements
 */
export function stableSort<T>(array: T[], comparator: (a: T, b: T) => number): T[] {
  const stabilizedThis = array.map((el, index) => [el, index] as [T, number]);
  stabilizedThis.sort((a, b) => {
    const order = comparator(a[0], b[0]);
    if (order !== 0) return order;
    return a[1] - b[1];
  });
  return stabilizedThis.map((el) => el[0]);
}

/**
 * Get Python type string from JavaScript value
 */
export function getPythonTypeString(obj: any): string | undefined {
  if (typeof obj === 'number') {
    return REAL_TYPE.FLOAT;
  }
  if (typeof obj === 'string') {
    return REAL_TYPE.STR;
  }
  if (typeof obj === 'boolean') {
    return REAL_TYPE.BOOL;
  }
  return undefined;
}

